package org.note.law.utils;

import cn.hutool.core.bean.BeanUtil;
import org.note.law.domain.MarkdownNode;
import org.note.law.module.provision.LawProvision;
import org.note.law.module.provision.LawProvisionService;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MarkdownParser {

    private static final Pattern HEADER_PATTERN = Pattern.compile("^(#{1,6})\\s+(.*)$", Pattern.MULTILINE);

    public static MarkdownNode parse(String content) throws IOException {
        Matcher matcher = HEADER_PATTERN.matcher(content);

        MarkdownNode root = new MarkdownNode("root", 0);
        List<MarkdownNode> nodeStack = new ArrayList<>();
        nodeStack.add(root);

        int lastIndex = 0;

        while (matcher.find()) {
            // Extract content between headers
            String previousContent = content.substring(lastIndex, matcher.start()).trim();
            if (!nodeStack.isEmpty() && !previousContent.isEmpty()) {
                nodeStack.get(nodeStack.size() - 1).appendContent(previousContent);
            }
            lastIndex = matcher.end();

            // Extract header information
            int level = matcher.group(1).length();
            String title = matcher.group(2);

            MarkdownNode node = new MarkdownNode(title, level);

            // Find the correct parent for the current node
            while (nodeStack.get(nodeStack.size() - 1).getLevel() >= level) {
                nodeStack.remove(nodeStack.size() - 1);
            }

            nodeStack.get(nodeStack.size() - 1).addChild(node);
            nodeStack.add(node);
        }

        // Append remaining content after the last header
        if (lastIndex < content.length()) {
            String remainingContent = content.substring(lastIndex).trim();
            if (!remainingContent.isEmpty()) {
                nodeStack.get(nodeStack.size() - 1).appendContent(remainingContent);
            }
        }

        return root;
    }

    public static void flattenTreeHelper(MarkdownNode node, List<LawProvision> list) {
        LawProvision lawProvision = new LawProvision();
        lawProvision.setTitle(node.getTitle());
        lawProvision.setLevel(node.getLevel());
        lawProvision.setContent(node.getContent());
        list.add(lawProvision); // 将当前节点添加到列表中
        for (MarkdownNode child : node.getChildren()) {
            flattenTreeHelper(child, list); // 递归处理子节点
        }
    }

    public static void printTree(MarkdownNode node, String indent) {
        System.out.println(indent + node.getTitle() + " (" + node.getLevel() + ")");
        System.out.println(indent + "Content: " + node.getContent());
        for (MarkdownNode child : node.getChildren()) {
            printTree(child, indent + "  ");
        }
    }

}
